package com.example.langchain4j.repository;

import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import java.time.Duration;
import java.util.List;
//此类为做聊天信息数据持久化的类，为了打破Langchain4j原有的存在数组中的方式我们创建了RedisChatMemoryStore类来重写这三个存储方式将聊天内容存储在Redis中
@Repository
public class RedisChatMemoryStore implements ChatMemoryStore {
    @Resource
//    private StringRedisTemplate redisTemplate;  是错的，因为Resource是按名称寻找bean，去找的的第一个bean是redisTemplate而不是StringRedisTemplate，所以这里不能用Resource，要用Autowired
    private StringRedisTemplate stringRedisTemplate;
//    记录学习，Autowired和Resource注解的区别，Autowired是按类型注入，Resource是按名称注入

    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        String json = stringRedisTemplate.opsForValue().get(memoryId);
            return ChatMessageDeserializer.messagesFromJson(json);
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> list) {
        String json = ChatMessageSerializer.messagesToJson(list);
        stringRedisTemplate.opsForValue().set(memoryId.toString(),json , Duration.ofDays(1));
    }

    @Override
    public void deleteMessages(Object memoryId) {
        stringRedisTemplate.delete(memoryId.toString());
    }
}
